#include "InstantReplayThread.h"

namespace jcrada {

    InstantReplayThread::InstantReplayThread(int evaluation_time):
    _evaluation_time(evaluation_time){
//        setSecondsForStabilization(10);
    }
    
    InstantReplayThread::~InstantReplayThread(){
        for (int i = 0 ; i < _creatures.size(); ++i){
            delete _creatures.at(i);
        }
    }

    void InstantReplayThread::run() {
        emit started();
        QTime timer;
        timer.start();
        iterate();
        setStopped(true);
        emit stopped();
        emit message(QString(("Time Elapsed: " + TO_STRING(timer.elapsed() / 1000.0) + " s.").c_str()));
    }
    

    void InstantReplayThread::iterate() {
        if (_creatures.empty()) {
            emit message("Creatures not loaded");
            setStopped(true);
            return;
        }
        int simulation_steps = getEvaluationTime() * getSimulator().getTimestepsPerSecond();
        Creature* creature = NULL;
        double fitness = 0.0;
        for (int i = 0; i < _creatures.size(); ++i) {
            creature = _creatures.at(i);
            getSimulator().reset();
            creature->reset();
            creature->set();
            getSimulator().addCreature(*creature);
            stabilize(*creature);
            for (int j = 0; j < simulation_steps; ++j) {
                getTimer().restart();
                performStep();
                ensureFrameRate(getTimer().elapsed());
            }
            getSimulator().removeCreature();
            creature->setFitness((creature->getFinalPosition() - creature->getInitialPosition()).length());
            fitness += creature->getFitness();
            emit message((TO_STRING(i) + "\t" + TO_STRING(creature->getFitness())).c_str());
        }
        std::string m = TO_STRING(getCurrentIteration()) +
                "\t" + TO_STRING(fitness / _creatures.size());
        emit message(QString(m.c_str()));
    }
}
